package day19;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileStreamDemo {

	public static void main(String[] args) {
		// read_1();
		// read_2();
		read_3();
		// write();
	}

	// 不建议使用这种方式，因为一般用字节流读取的数据都比较多，容易造成内存溢出
	public static void read_3() {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("stream.txt");
			// fis.available()方法返回文件的字符长度
			byte[] buf = new byte[fis.available()];
			int len = fis.read(buf);
			System.out.print(new String(buf, 0, len));

		} catch (FileNotFoundException e) {
			throw new RuntimeException("未找到要操作的文件！");
		} catch (IOException e) {
			throw new RuntimeException("读取文件失败！");
		} finally {
			if (null != fis) {
				try {
					fis.close();
				} catch (IOException e) {
					throw new RuntimeException("字节读取流关闭失败！");
				}
			}
		}
	}

	public static void read_2() {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("stream.txt");
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = fis.read(buf)) != -1) {
				System.out.print(new String(buf, 0, len));
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException("未找到要操作的文件！");
		} catch (IOException e) {
			throw new RuntimeException("读取文件失败！");
		} finally {
			if (null != fis) {
				try {
					fis.close();
				} catch (IOException e) {
					throw new RuntimeException("字节读取流关闭失败！");
				}
			}
		}
	}

	public static void read_1() {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("stream.txt");
			int ch = 0;
			while ((ch = fis.read()) != -1) {
				System.out.print((char) ch);
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException("未找到要操作的文件！");
		} catch (IOException e) {
			throw new RuntimeException("读取文件失败！");
		} finally {
			if (null != fis) {
				try {
					fis.close();
				} catch (IOException e) {
					throw new RuntimeException("字节读取流关闭失败！");
				}
			}
		}

	}

	public static void write() {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream("stream.txt");
			fos.write("abcdefg".getBytes());
		} catch (FileNotFoundException e) {
			throw new RuntimeException("文件未找到！");
		} catch (IOException e) {
			throw new RuntimeException("文件写入失败！");
		} finally {
			if (null != fos) {
				try {
					fos.close();
				} catch (IOException e) {
					throw new RuntimeException("字节写入流关闭失败！");
				}
			}
		}
	}
}
